package com.lw.leetcode.linked.c;

import com.lw.leetcode.linked.ListNode;

/**
 * Created with IntelliJ IDEA.
 * 25. K 个一组翻转链表
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/11 11:45
 */
public class ReverseKGroup {
    public ListNode reverseKGroup(ListNode head, int k) {
        int length = 0;
        ListNode l = head;
        while (l != null) {
            length++;
            l = l.next;
        }
        if (length == 0) {
            return head;
        }
        int limit = length / k;
        ListNode a = new ListNode(0);
        a.next = head;
        ListNode f = a;
        int n;
        int count = 0;
        ListNode pr;
        ListNode item;
        ListNode zh;
        ListNode d;
        while (count < limit) {
            count++;
            n = 2;
            pr = f.next;
            item = pr.next;
            d = f.next;
            while (n <= k) {
                n++;
                zh = item.next;
                item.next = pr;
                pr = item;
                item = zh;
            }
            f.next = pr;
            d.next = item;
            f = d;
        }
        return a.next;
    }
}
